#!/bin/bash
exec_name=EttaM1
install_dir=~/$exec_name

check_version() {
  if [ -L $install_dir/$exec_name ]; then
     local install_version_dir=`dirname $(readlink $install_dir/$exec_name)`
     local install_version=`basename $install_version_dir`
     local current_version_dir=`dirname $(pwd)`
     local current_version=`basename $current_version_dir`
     if [ ! x"$current_version" == x"$install_version" ]; then
       echo -e "\033[1;31merror:\033[0m" "'$current_version' is not installed."
       echo -e "found: '$install_version' use '\033[1;36mbash uninstall.sh -f\033[0m' uninstall"
       exit 255
     fi
  fi
}

cancel_autostart() {
local autostart_script_1=/etc/profile.d/${exec_name}*.sh
local autostart_script_2=/etc/xdg/autostart/${exec_name}*.desktop
local autostart_script_3=~/.config/autostart/${exec_name}*.desktop
local cancel_fail_message="\033[1;31merror:\033[0m '${exec_name}' autostart cancel fail."

echo 123 | sudo -S rm -f ${autostart_script_1} >/dev/null 2>&1
echo 123 | sudo -S rm -f ${autostart_script_2} >/dev/null 2>&1
echo 123 | sudo -S rm -f ${autostart_script_3} >/dev/null 2>&1
[ -f ${autostart_script_1} ] && { echo -e ${cancel_fail_message}; exit 1; }
[ -f ${autostart_script_2} ] && { echo -e ${cancel_fail_message}; exit 2; }
[ -f ${autostart_script_3} ] && { echo -e ${cancel_fail_message}; exit 3; }
}

remove_apps_icon() {
local desktop_file_1=~/Desktop/${exec_name}*.desktop
local desktop_file_2=~/.local/share/applications/${exec_name}*.desktop
local remove_fail_message="\033[1;31merror:\033[0m '${exec_name}' remove application icon fail."

echo 123 | sudo -S rm -f ${desktop_file_1} >/dev/null 2>&1
echo 123 | sudo -S rm -f ${desktop_file_2} >/dev/null 2>&1
[ -f ${desktop_file_1} ] && { echo -e ${remove_fail_message}; exit 4; }
[ -f ${desktop_file_2} ] && { echo -e ${remove_fail_message}; exit 5; }
}

remove_install_version() {
if [ -L $install_dir/$exec_name ]; then
  local install_version_dir_path=`dirname $(readlink $install_dir/$exec_name)`
  local install_version_dir_name=`basename $install_version_dir_path`

  # remove link file
  rm -f $install_dir/$exec_name
  [  -f $install_dir/$exec_name ] && { echo -e "\033[1;31merror:\033[0m '${exec_name}' uninstall fail."; exit 6; }

  cd $install_version_dir_path/../

  # backup current install version
  tar -zcvf $install_version_dir_path.tar.gz $install_version_dir_name/ 2>/dev/null
  if [ $? -eq 0 ]; then
    # remove software directory
    rm -rf $install_version_dir_path/ >/dev/null 2>&1
  fi

  cd - >/dev/null 2>&1 || { echo >/dev/null; }
fi
}


for i in "$@"; do
  if [ "${i}" == "-f" ]; then
    option="skip-check-version"
    break
  fi
done

case $option in
  "skip-check-version")
    cancel_autostart
    remove_apps_icon
    remove_install_version
    ;;

  *)
    check_version
    cancel_autostart
    remove_apps_icon
    remove_install_version
    ;;
esac
